document.addEventListener('DOMContentLoaded', function() {
  const exportBtn = document.getElementById('exportBtn');
  const statusDiv = document.getElementById('status');

  exportBtn.addEventListener('click', async () => {
    try {
      statusDiv.textContent = '正在加载全部视频...';
      // 获取当前标签页
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      // 先自动滚动加载全部视频
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: autoScrollToLoadAllVideos
      });
      statusDiv.textContent = '正在获取视频链接...';
      // 获取所有视频链接
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: getVideoLinks
      });
      const videoLinks = results[0].result;
      if (videoLinks.length === 0) {
        statusDiv.textContent = '未找到视频链接';
        return;
      }
      // 加BOM防乱码
      const csvContent = '\uFEFF' + createCSV(videoLinks);
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      // 下载到统一文件夹
      await chrome.downloads.download({
        url: url,
        filename: `抖音视频导出/抖音视频链接_${timestamp}.csv`
      });
      statusDiv.textContent = `成功导出 ${videoLinks.length} 个视频链接`;
    } catch (error) {
      statusDiv.textContent = '导出失败：' + error.message;
    }
  });
});

// 自动滚动加载全部视频
function autoScrollToLoadAllVideos() {
  return new Promise((resolve) => {
    let lastCount = 0;
    let sameCountTimes = 0;
    function scroll() {
      window.scrollTo(0, document.body.scrollHeight);
      setTimeout(() => {
        const currentCount = document.querySelectorAll('li.SmHs0qqX a.hY8lWHgA').length;
        if (currentCount > lastCount) {
          lastCount = currentCount;
          sameCountTimes = 0;
          scroll();
        } else {
          sameCountTimes++;
          if (sameCountTimes > 3) {
            resolve();
          } else {
            scroll();
          }
        }
      }, 1000);
    }
    scroll();
  });
}

// 获取所有视频链接
function getVideoLinks() {
  const videoElements = document.querySelectorAll('li.SmHs0qqX a.hY8lWHgA');
  const videos = [];
  videoElements.forEach(element => {
    const videoUrl = element.href;
    const title = element.querySelector('.ztA3qIFr')?.textContent || '';
    const likes = element.querySelector('.b3Dh2ia8')?.textContent || '0';
    videos.push({
      url: videoUrl,
      title: title,
      likes: likes
    });
  });
  return videos;
}

// 创建CSV内容
function createCSV(videos) {
  const headers = ['视频链接', '标题', '点赞数'];
  const rows = videos.map(video => [
    video.url,
    `"${video.title.replace(/"/g, '""')}"`,
    video.likes
  ]);
  return [headers, ...rows].map(row => row.join(',')).join('\n');
} 